<template>
  <div>
    <div>
      <ele-page
        v-loading="loading"
        :formConfig="searchConfig"
        ref="eleTable"
        :operateList="operateList"
        @handleOperateEvent="handleOperateEvent"
        :column="column"
        :getList="getList"
        uniqueId="wmsOrderCheckTemplateTable"
      >
      </ele-page>
    </div>
    <ele-form-drawer class="dialog-pack" size="50%" :isLoading="isLoading" v-model="formDataDialog" v-bind="formDescDialog" :request-fn="handleSubmit" :visible.sync="visible" :title="title">
      <template v-slot:dpInterval>
        <div style="margin-top: 42px; display: flex;">
          <span>{{ $i18n.t('wmsOrderCheckTemplate.last') }}</span>
          <el-input-number style="margin: 0 6px;" v-model="formDataDialog.dpInterval" :controls="false" :min="1" />
          <span>{{ $i18n.t('wmsOrderCheckTemplate.day') }}</span>
        </div>
      </template>
      <template v-slot:table2>
        <el-row>
          <el-col :span="20">
            <label for="" style="padding-right: 20px;"><span></span>{{ '盘点物料筛选'}}</label>
            <el-select v-model="formDataDialog.materialRestrictions" :placeholder="$i18n.t('common.select')" @change="() => (formDataDialog.table2 = [])">
              <el-option v-for="item in wms_pd_material_restrictions" :key="item.value" :label="item.description" :value="item.value"> </el-option> </el-select
          ></el-col>
          <el-col :span="4" style="display: flex; justify-content: flex-end;">
            <el-button type="primary" v-if="formDataDialog.materialRestrictions && formDataDialog.materialRestrictions != '10'" @click="openMaterialModal(2)">{{ $i18n.t('common.add2') }}</el-button>
          </el-col>
        </el-row>
        <el-table
          v-if="formDataDialog.materialRestrictions && formDataDialog.materialRestrictions != '10'"
          ref="placeTable"
          :data="formDataDialog.table2"
          tooltip-effect="dark"
          style="margin-top: 10px;"
        >
          <el-table-column type="selection" width="55" align="center"> </el-table-column>
          <el-table-column :label="setColumns('wms_pd_material_restrictions', formDataDialog.materialRestrictions)" prop="name" align="center"> </el-table-column>
          <el-table-column :label="$i18n.t('common.operation')" align="center">
            <template slot-scope="scope">
              <el-button size="mini" style="color: #f56c6c;" type="text" @click="deleteRow(scope.$index, formDataDialog.table2)">{{ $i18n.t('common.delete') }}</el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>
      <template v-slot:table3 v-if="formDataDialog.isAppoint">
          <!-- 插槽内容有el-form-item组件包裹 -->
          <el-input
            v-model="formDataDialog.personName"
            readonly
            :placeholder="$t('common.select')"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="baseUserDialogVisible = true"
            ></el-button>
          </el-input>
      </template>
    </ele-form-drawer>
    <ele-dialog-table
      :title="modalTitle"
      width="1000px"
      ref="dialogGoods"
      :visible.sync="goodsDialogVisible"
      :formConfig="goodsSearchDialog"
      :column="goodsDialogColumn"
      @getSelectData="getSelectData"
      :otherParam="otherParam"
      :getList="getListByType"
    >
    </ele-dialog-table>
    <ele-dialog-table
      :title="modalTitle"
      width="1000px"
      ref="dialogPlace"
      :visible.sync="placeDialogVisible"
      :formConfig="placeSearchDialog"
      :column="placeDialogColumn"
      @getSelectData="getSelectplaceData"
      :otherParam="otherParam"
      :getList="getPlaceList"
    >
    </ele-dialog-table>
    <ele-dialog-table
      title="用户信息查询"
      width="800px"
      class="usermodalTable"
      :visible.sync="baseUserDialogVisible"
      :formConfig="baseUserSearchDialog"
      :column="baseUserDialogColumn"
      @getSelectData="getSelectBaseUser"
      :otherParam="otherParam"
      :getList="getUserListByRoleIdAndFactory"
      :transFormdata="transFormdata"
      ref="modelTable"
    >
    </ele-dialog-table>
  </div>
</template>

<script>
import { operateList, searchConfig, formConfig, rowConfig,userMixin } from './config'
import {
  getList,
  rowCreate,
  rowUpdate,
  rowDel,
  rowDetail,
  getLocationRestrictionsList,
  getMaterialRestrictionsList,
  getTemplateTypeList,
  getDpFlagList,
  getTriggerMethodList,
  getTypeList,
  getMpFlagList,
  getsnControlList,
  getEnableStatusList,
  generateTask,
  deactivate,
  enable
} from '@/api/checkorder/mesOrderCheckTemplate'
import { getAreaCodeList, getCurrentWarehouseCode } from '@/api/outbound/wmsOutTaskDetail'
import { getDict } from '@/api/common'
export default {
  name: 'mesOrderCheckTemplate',
  mixins: [formConfig,userMixin],
  data() {
    return {
      modalTitle: '',
      title: null,
      visible: false,
      isLoading: false,
      loading: false,
      formDataDialog: {},
      otherParam:{roleIds:'1840200220378427394'},
      searchConfig,
      operateList,
      getList,

      // 列表页字段的绑定配置
      column: [
        {
          type: 'selection'
        },
        {
          type: 'index',
          label: $i18n.t('common.order'),
          fixed: 'left',
          width: 60
        },
        {
          prop: 'templateName',
          fixed: 'left',
          width: 160,
          label: "盘点模板", // 模板名称
          showOverflowTooltip: true
        },
        {
          prop: 'warehouseCode',
          label: $i18n.t('common.warehouseName'), // 仓库编码
          fixed: 'left',
          width: 180,
          showOverflowTooltip: true,
          optionProp: {
            value: 'modelingCode',
            label: 'modelingName'
          },
          option: async (data) => {
            const list = await getCurrentWarehouseCode()
            return list.data.result
          }
        },
        {
          prop: 'isAppoint',
          label: $i18n.t('是否指定人'), // 启用状态
          width: 120,
          showOverflowTooltip: true,
          render: (h, { row }) => {
            return <el-tag type={row.isAppoint == 1 ? 'success' : 'info'}>{row.isAppoint == 1 ?'指定' :'不指定' }</el-tag>
          }
        },
        {
          prop: 'personName',
          label: $i18n.t('指定人名称'), // 启用状态
          width: 120,
          showOverflowTooltip: true,
        },
        {
          prop: 'executeTime',
          width: 160,
          showOverflowTooltip: true,
          label: "上次执行时间" // 上次执行时间
        },
        {
          prop: 'executeByName',
          minWidth: 130,
          showOverflowTooltip: true,
          label: "上次执行人" // 上次执行人
        },
        {
          prop: 'enableStatus',
          label: $i18n.t('common.status'), // 启用状态
          width: 120,
          fixed: 'right',
          showOverflowTooltip: true,
          render: (h, { row }) => {
            return <el-tag type={row.enableStatus == 1 ? 'success' : 'info'}>{row.enableStatus == 1 ?'启用' :'停用' }</el-tag>
          }
        },
        {
          prop: 'createByName',
          label: $i18n.t('common.createByName'), // 创建人名称
          width: 130,
          showOverflowTooltip: true
        },
        {
          prop: 'createTime',
          label: $i18n.t('common.createTime'), // 创建时间
          width: 160,
          showOverflowTooltip: true
        },
        {
          prop: 'updateByName',
          label: $i18n.t('common.updateByName'), // 更新人名称
          width: 130,
          showOverflowTooltip: true
        },
        {
          prop: 'updateTime',
          label: $i18n.t('common.updateTime'), // 更新时间
          width: 160,
          showOverflowTooltip: true
        },

        {
          prop: 'operate',
          label: $i18n.t('common.operation'), // 操作
          width: 160,
          fixed: 'right',
          render: (h, scope) => {
            return <ele-row-operation scope={scope} rowConfig={rowConfig} onRowOperate={this.rowOperate} />
          }
        }
      ],
      wms_pd_material_restrictions: [],
      // wms_pd_location_restrictions: [],
      wms_week: []
    }
  },
  computed: {
    setColumns() {
      return function (options, val) {
        return this[options].find((i) => i.value == val).description
      }
    }
  },
  created() {
    // this.getDict('wms_pd_location_restrictions')
    this.getDict('wms_pd_material_restrictions')
    this.getDict('wms_week')
  },
  methods: {
    transFormdata(data) {
      return  Promise.resolve({records: data.data.result});
    },
    getDict(type) {
      getDict(type).then((res) => {
        const data = res.data.result || []
        this[type] = data
      })
    },
    //表格顶部按钮操作事件
    handleOperateEvent(data) {
      this.title = data.name
      const fnc = {
        add: () => {
          this.disableFields(false)
          this.formDataDialog = {
            materialRestrictions: '10',
            locationRestrictions: '10',
            enableStatus: 1,
            snControl: 'Y',
            dpFlag: 0,
            mpFlag: 0
          }
          this.visible = true
        },
        deleteBatch: () => {
          this.$confirm('此操作将批量删除盘点模板, 是否继续?', $i18n.t('common.tip'), {
            confirmButtonText: $i18n.t('common.submit'),
            cancelButtonText: $i18n.t('common.cancel'),
            type: 'warning'
          }).then(() => {
            const ids = data.rows.map((val) => val.id).join(',')
            this.rowDel(ids)
          })
        },
        createTask: () => {
          this.$confirm('此操作将创建盘点单, 是否继续?', $i18n.t('common.tip'), {
            confirmButtonText: $i18n.t('common.ok'),
            cancelButtonText: $i18n.t('common.cancel'),
            type: 'warning'
          }).then(() => {
            this.generateTask(data.rows[0])
          })
        },
        deactivated: () => {
          this.$confirm('此操作将启用该盘点模板, 是否继续?', $i18n.t('common.tip'), {
            confirmButtonText: $i18n.t('common.ok'),
            cancelButtonText: $i18n.t('common.cancel'),
            type: 'warning'
          }).then(() => {
            this.enableOrDeactivated(deactivate, { id: data.rows[0].id }, '停用成功')
          })
        },
        enabled: () => {
          this.$confirm('此操作将启用该盘点模板, 是否继续?', $i18n.t('common.tip'), {
            confirmButtonText: $i18n.t('common.ok'),
            cancelButtonText: $i18n.t('common.cancel'),
            type: 'warning'
          }).then(() => {
            this.enableOrDeactivated(enable, { id: data.rows[0].id }, '启用成功!')
          })
        }
      }
      fnc[data.handleName]()
    },
    // 生成盘点任务
    generateTask(row) {
      this.loading = true
      generateTask({ id: row.id, templateName: row.templateName })
        .then((res) => {
          const message = res.data.message
          this.$message.success(message || $i18n.t('common.operateSuccess'))
          this.visible = false
          this.refresh()
        })
        .finally(() => {
          this.loading = false
        })
    },
    //表格行操作事件
    rowOperate({ handleName, name, row }) {
      this.title = name
      const fnc = {
        edit: () => {
          this.disableFields(false)
          this.rowDetail(row.id)
        },
        detail: () => {
          this.disableFields(true)
          this.rowDetail(row.id)
        },
        delete: () => {
          this.$confirm($i18n.t('此操作将删除该盘点模板, 是否继续?'), $i18n.t('common.tip'), {
            confirmButtonText: $i18n.t('common.ok'),
            cancelButtonText: $i18n.t('common.cancel'),
            type: 'warning'
          }).then(() => {
            this.rowDel(row.id)
          })
        }
      }
      fnc[handleName]()
    },
    enableOrDeactivated(api, data, title) {
      this.loading = true
      api(data)
        .then((res) => {
          const message = res.data.message
          this.$message.success(message || title)

          this.refresh()
        })
        .finally(() => {
          this.loading = false
        })
    },
    doSubmit({ title, api, data }) {
      console.log(data)
      this.isLoading = true
      api(data)
        .then((res) => {
          const message = res.data.message
          this.$message.success(message || title)
          this.visible = false
          this.refresh()
        })
        .finally(() => {
          this.isLoading = false
        })
    },
    //弹框提交事件
    handleSubmit(data) {
      console.log(data, 'xxx')
      if (this.isLoading) return // 判断状态

      let formData = {
        templateName: data.templateName,
        warehouseCode: data.warehouseCode,
        triggerMethod: data.triggerMethod,
        triggerUnit: data.triggerUnit,
        triggerYear: data.triggerUnit == 'year' ? `${data.triggerDate} ${data.triggerLocalTime}` : null,
        triggerDay: data.triggerUnit == 'month' ? data.triggerDay : null,
        triggerWeek: data.triggerUnit == 'week' ? data.triggerWeek : null,
        triggerLocalTime: data.triggerLocalTime,
        templateType: data.templateType,
        argumentsType: data.templateType == '30' ? data.argumentsType : null,
        arguments: data.templateType == '10' ? null : data.templateType == '20' ? data.cycle1 : data.cycle2,
        dpFlag: `${data.dpFlag}` || '0',
        dpType: data.dpFlag == '1' ? data.dpType : null,
        dpInterval: data.dpType == '3' ? data.dpInterval : null,
        mpFlag: `${data.mpFlag}` || '0',
        mpWay: data.mpFlag ? data.mpWay : null,
        enableStatus: `${data.enableStatus}` || '1',
        isAppoint: `${data.isAppoint}` || '1',
        personCode: data.personCode,
        personName: data.personName,
        numberOfResets: data.numberOfResets,
        locationRestrictions: data.locationRestrictions,
        materialRestrictions: data.materialRestrictions,
        remark: data.remark
      }
      if (this.formDataDialog.id) formData.id = this.formDataDialog.id
      if (data.locationRestrictions != '10') {
        if (!this.formDataDialog.table1 || !this.formDataDialog.table1.length) {
          return this.$message.error($i18n.t('wmsOrderCheckTemplate.listNotEmptyHint1'))
        }
        const map1 = { 20: 'area', 30: 'location', 40: 'locationGroup' }
        formData[`${map1[data.locationRestrictions]}List`] = this.formDataDialog.table1.map((i) => {
          return {
            [`${map1[data.locationRestrictions]}Code`]: i.code,
            [`${map1[data.locationRestrictions]}Name`]: i.name
          }
        })
      }
      if (data.materialRestrictions != '10') {
        if (!this.formDataDialog.table2 || !this.formDataDialog.table2.length) {
          return this.$message.error($i18n.t('wmsOrderCheckTemplate.listNotEmptyHint2'))
        }
        const map2 = {
          20: {
            l: 'materialList',
            f: 'goods'
          },
          30: {
            l: 'materialGroupList',
            f: 'series'
          }
        }
        formData[map2[data.materialRestrictions].l] = this.formDataDialog.table2.map((i) => {
          return {
            [`${map2[data.materialRestrictions].f}Code`]: i.code,
            [`${map2[data.materialRestrictions].f}Name`]: i.name
          }
        })
      }
      const params = this.formDataDialog.id
        ? {
            title: $i18n.t('common.editSuccess'),
            api: rowUpdate,
            data: formData
          }
        : {
            title: $i18n.t('common.addSuccess'),
            api: rowCreate,
            data: formData
          }
      this.doSubmit(params)
    },
    //删除
    rowDel(data) {
      this.loading = true
      rowDel(data)
        .then((res) => {
          const message = res.data.message
          this.$message.success(message || $i18n.t('common.deleteSuccess'))
          this.refresh()
        })
        .finally(() => {
          this.loading = false
        })
    },
    disableFields(flag) {
      this.formDescDialog.disabled = flag
      this.formDescDialog.isShowSubmitBtn = !flag
    },
    // 处理限制列表数据
    handleList(arr = [], code, label) {
      return arr.map((i) => {
        return {
          name: i[label],
          code: i[code]
        }
      })
    },
    // 详情
    rowDetail(id) {
      rowDetail(id)
        .then((res) => {
          console.log(res.data.result)
          const data = res.data.result || {}

          let table1 =
            data.locationRestrictions == '20'
              ? this.handleList(data.areaList, 'areaCode', 'areaDesc')
              : data.locationRestrictions == '30'
              ? this.handleList(data.locationList, 'locationCode', 'locationCode')
              : this.handleList(data.locationGroupList, 'locationGroupCode', 'locationGroupCode')
          let table2 = data.materialRestrictions == '20' ? this.handleList(data.materialList, 'goodsCode', 'goodsName') : this.handleList(data.materialGroupList, 'seriesCode', 'seriesName')
          const nowYear = new Date().getFullYear()
          this.formDataDialog = {
            ...data,
            triggerDate: data.triggerUnit == 'year' && data.triggerYear ? nowYear + '-' + data.triggerYear.split(' ')[0].split('-')[1] + '-' + data.triggerYear.split(' ')[0].split('-')[2] : null,
            triggerLocalTime: data.triggerUnit == 'year' && data.triggerYear ? data.triggerYear.split(' ')[1] : data.triggerLocalTime,
            cycle1: data.templateType == '20' ? data.arguments : null,
            cycle2: data.templateType == '30' ? data.arguments : null,
            table1: table1 || [],
            table2: table2 || [],
            mpFlag: data.mpFlag ? Number(data.mpFlag) : 0,
            enableStatus: data.enableStatus ? Number(data.enableStatus) : 1,
            dpFlag: data.dpFlag ? Number(data.dpFlag) : 0,
            snControl: data.snControl ? data.snControl : 'N',
            isAppoint: data.isAppoint ? Number(data.isAppoint) : 1,
            personCode: data.personCode,
            personName: data.personName,
          }
        })
        .finally(() => {
          this.visible = true
        })
    },
    //刷新表格数据
    refresh(isReset = true) {
      this.$refs.eleTable.refresh(isReset)
    }
  }
}
</script>
